package com.comm.tools;

import java.io.File;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileService
{
  public static ArrayList<File> getFiles(String s)
  {
    return getFiles("./", s);
  }

  public static ArrayList<File> getFiles(String dir, String s)
  {
    File file = new File(dir);

    s = s.replace('.', '#');
    s = s.replaceAll("#", "\\\\.");
    s = s.replace('*', '#');
    s = s.replaceAll("#", ".*");
    s = s.replace('?', '#');
    s = s.replaceAll("#", ".?");
    s = "^" + s + "$";

    Pattern p = Pattern.compile(s);
    ArrayList<File> list = filePattern(file, p);
    return list;
  }

  private static ArrayList<File> filePattern(File file, Pattern p)
  {
    if (file == null) {
      return null;
    }
    if (file.isFile()) {
      Matcher fMatcher = p.matcher(file.getName());
      if (fMatcher.matches()) {
        ArrayList<File> list = new ArrayList<File>();
        list.add(file);
        return list;
      }
    }
    else if (file.isDirectory()) {
      File[] files = file.listFiles();
      if ((files != null) && (files.length > 0)) {
        ArrayList<File> list = new ArrayList<File>();
        for (int i = 0; i < files.length; i++) {
          ArrayList<File> rlist = filePattern(files[i], p);
          if (rlist != null) {
            list.addAll(rlist);
          }
        }
        return list;
      }
    }
    return null;
  }
}
